package com.antaohua.platfrom.framework.web.config.initializer;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import com.antaohua.platfrom.framework.web.filter.LoggerMDCFilter;

public class WebInitializer implements WebApplicationInitializer{

	
	
	
	private WebInitializer initLoadLoggerMDCFilter(ServletContext servletContext) {
	     FilterRegistration.Dynamic loggerFilter = servletContext.addFilter("LoggerMDCFilter", new LoggerMDCFilter());
	     loggerFilter.addMappingForUrlPatterns(null, true, new String[] { "/*" });
	     return this;
	}
	
	private WebInitializer initSpringApplicationContext(ServletContext servletContext){
	     AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
	     rootContext.scan(new String[] { "com.antaohua.platfrom.**.config"});
	     servletContext.addListener(new ContextLoaderListener(rootContext));
	     return this;
	}
	
	
	private WebInitializer initSpringMvcContext(ServletContext servletContext){
	     AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	     dispatcherContext.scan(new String[] { "com.antaohua.platfrom.**.web.webconfig"});
	     ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
	     dispatcher.setLoadOnStartup(1);
	     dispatcher.addMapping(new String[] { "*.json" });
	     return this;
	}
	
	
	private WebInitializer initEncodingFilter(ServletContext servletContext) {
		 CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
	     encodingFilter.setEncoding("UTF-8");
	     encodingFilter.setForceEncoding(true);
	     FilterRegistration.Dynamic fr = servletContext.addFilter("encodingFilter", encodingFilter);
	     EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class);
	     fr.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
	     return this;
	}
	
	

	

	
	
	@Override
	public void onStartup(ServletContext paramServletContext)throws ServletException {
		initLoadLoggerMDCFilter(paramServletContext).
		initSpringApplicationContext(paramServletContext).
		initEncodingFilter(paramServletContext).
		initSpringMvcContext(paramServletContext);
	}
	
}
